﻿using System;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Text;
using System.Windows;
using DiagnosticCenter.View;

namespace DiagnosticCenter.ViewModel
{
    static class vmTools
    {
        private static readonly AuthenticationService AuthService = WebContext.Current.Authentication;

        //Проверка на четность
        public static bool IsEven(int x)
        {
            return (x & 1) == 0;
        }

        public static void DoLogin(string Login, string Password)
        {
            Password = MD5Encryption(Password);
            var lp = new LoginParameters(Login, Password, true, null);
            AuthService.Login(lp, LoginOperation_Completed, null);
        }

        private static void LoginOperation_Completed(LoginOperation lo)
        {
            if (lo.HasError)
            {
                var errorWin = new ErrorWindow(lo.Error);
                errorWin.Show();
                lo.MarkErrorAsHandled();
            }
            else if (lo.LoginSuccess == false)
            {
                var errorWin = new ErrorWindow("Ошибка авторизации", "Проверьте логин и пароль");
                errorWin.Show();
            }
            else if (lo.LoginSuccess)
            {
                var mp = (MainPage)Application.Current.RootVisual;
                switch (WebContext.Current.User.Role)
                {
                    case "2":
                        //mp.mainFrame.Navigate(new Uri("/View/viewOperator.xaml", UriKind.Relative));
                        mp.mainFrame.Navigate(new Uri("/View/viewTesting.xaml", UriKind.Relative));
                        break;
                    case "3":
                        mp.mainFrame.Navigate(new Uri("/View/viewStudent.xaml", UriKind.Relative));
                        break;
                }
            }
        }

        public static string MD5Encryption(string Data)
        {
            var decoder = new UTF8Encoding();
            var target = decoder.GetBytes(Data);
            return BitConverter.ToString(MD5Core.GetHash(target)).Replace("-", "");;
        }
    }
}
